/* 配置路由 */
// 导入路由页面
import Home from '@views/home/index.vue'
import Login from '@views/login/index.vue'
import {createRouter, createWebHistory, NavigationGuardNext, RouteLocationNormalized, RouteRecordRaw} from "vue-router";
import dashboard from "./modules/dashboard.ts";

const modules = import.meta.glob('./modules/**/*.ts', {eager: true})
const routeModuleList: RouteRecordRaw[] = [];
Object.keys(modules).forEach((key: string) => {
    const mod = modules[key].default || {};
    const modList = Array.isArray(mod) ? [...mod] : [mod];
    routeModuleList.push(...modList)
})
// 路由规则
const routes = [
    {path: '/', name: "home", component: Home, meta: {title: '首页'}},
    {path: '/login', name: "login", component: Login, meta: {title: '登录'}}
]

const baseRoutes = [...routes, ...dashboard]
// 配置路由
export const router = createRouter({
    history: createWebHistory(),
    routes: baseRoutes,
})

// 配置导航守卫
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
    // 设置网站标题
    document.title = `${to.meta.title} | V3+TS - admin` || document.title

    // 判断是否需要登录
    if (to.name !== 'login' && !localStorage.getItem('token')) {
        next({
            name: 'login',
            query: {redirect: to.fullPath}
        })
    } else {
        next()
    }
})

export {routeModuleList}
export default router